﻿using System;
using System.Web.UI;

namespace ASPNETVN.PORTAL.Components.Share.Controls
{
    public partial class Recaptcha : UserControl
    {

        private Random rnd = new Random();

        public string ValidationGroup { set; get; }
        public string LabelCheckCaption { set; get; }
        public string ButtonCheckCaption { set; get; }
        public bool IsValid { set; get; }

        // Delegate declaration
        public delegate void ValidateHandler(object sender, EventArgs e);
        public event ValidateHandler Validate;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            lblCheckCaption.Text = this.LabelCheckCaption;
            btnCheck.Text = this.ButtonCheckCaption;
            txtDigit.ValidationGroup = this.ValidationGroup;
            btnCheck.ValidationGroup = this.ValidationGroup;
            revDigit.ValidationGroup = this.ValidationGroup;
            rfvDigit.ValidationGroup = this.ValidationGroup;
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                CreateRecaptcha();
            }
        }

        private void CreateRecaptcha()
        {
            
            int digit1 = rnd.Next(0, 9);
            imgNumber1.ImageUrl = string.Format("~/Images/Icons/Numbers/{0}.jpg", digit1);

            int digit2 = rnd.Next(0, 9);
            imgNumber2.ImageUrl = string.Format("~/Images/Icons/Numbers/{0}.jpg", digit2);

            int digit3 = rnd.Next(0, 9);
            imgNumber3.ImageUrl = string.Format("~/Images/Icons/Numbers/{0}.jpg", digit3);

            int digit4 = rnd.Next(0, 9);
            imgNumber4.ImageUrl = string.Format("~/Images/Icons/Numbers/{0}.jpg", digit4);

            HiddenFieldCheck.Value = digit1 + "" + digit2 + "" + digit3 + "" + digit4;
        }

        protected void ButtonCheck_Click(object sender, EventArgs e)
        {
            if (Validate != null)
            {
                this.IsValid = txtDigit.Text == HiddenFieldCheck.Value;
                LabelMessage.Text = this.IsValid == false ? "Bạn đã nhập sai mã xác nhận" : string.Empty;

                Validate(sender, e);
                if (this.IsValid)
                {
                    txtDigit.Text = string.Empty;
                    CreateRecaptcha();
                }
            }
        }
    }
}